package com.tran.app.viewmodel

import android.text.TextUtils
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.orhanobut.logger.Logger
import com.tran.app.MyApp
import com.tran.app.dao.AppDatabase
import com.tran.app.data.Course
import com.tran.app.data.RegisterUi
import com.tran.app.utils.show
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

data class UiState(val course: Course,val isloading:Boolean=true)

class UpdateCourseViewModel:ViewModel() {
    private val _uidata = MutableStateFlow(UiState(Course()))
    val uidata: StateFlow<UiState> = _uidata.asStateFlow()


    fun setuidata(ui:UiState){
        _uidata.update {
            ui
        }
    }

    fun public(){
        viewModelScope.launch {
            if(TextUtils.isEmpty(uidata.value.course.exam)||
                TextUtils.isEmpty(uidata.value.course.credits)||
                TextUtils.isEmpty(uidata.value.course.name)||
                TextUtils.isEmpty(uidata.value.course.studyhour)
                ){
                show("输入不能为空")
                return@launch
            }
            withContext(Dispatchers.IO) {
                AppDatabase.getInstance(MyApp.instance).courseDao().update(course = _uidata.value.course)
            }
            withContext(Dispatchers.Main) {
                show("修改课程成功")
            }
        }
    }

    fun update(id: Int) {
        Logger.d("id=="+id)
        viewModelScope.launch {
            withContext(Dispatchers.IO){
                val course =AppDatabase.getInstance(MyApp.instance).courseDao().getCoursesById(id)
               _uidata.update {
                  it.copy(course = course,
                      isloading = false)
               }
            }
        }
    }

}